'use strict';

/**
 * mongoose 分页查询插件
 */
function pageQueryPlugin(schema) {

    /**
     *
     * @param paginationOption 分页配置参数 default value : {page:0,pageSize:25}
     * @param populate
     * @param queryParams 查询条件
     * @param fields 子段
     * @param sortParams 排序参数
     * @param callback 回调函数 function(err,results)
     * @returns {Promise<{pagination: {page: number|*, pageSize: *|number, rowCount: number, pageCount: number}, data: Array}>}
     */
    schema.statics.findPage = async function (paginationOption, populate, queryParams, fields, sortParams, callback) {

        const Model = this; //mongoose Model's static method
        const page = Number(paginationOption.page || pageQueryPlugin.defaultPaginationOption.page);
        const pageSize = Number(paginationOption.pageSize || pageQueryPlugin.defaultPaginationOption.pageSize);
        const start = (page - 1) * pageSize;

        let $page = { //初始化
            pagination: {
                page: page,
                pageSize: pageSize,
                rowCount: 0,
                pageCount: 0
            },
            data: []
        };

        try {

            let count = await Model.count(queryParams).exec();
            if (count > 0) {
                $page.pagination.rowCount = count;
                $page.pagination.pageCount = Math.ceil((count - 1) / pageSize + 1);
            }

            $page.data = await Model.find(queryParams).skip(start).limit(pageSize)
                .populate(populate).select(fields).sort(sortParams).exec();


            if (typeof callback === "function") {
               callback(null, $page);
            }

            return $page;

            // return new Promise((resolve, reject) => {
            //     resolve($page);
            // });

        } catch (err) {
            // return new Promise((resolve, reject) => {
            //     reject(err);
            // });

            return [];
        }
    }
}

pageQueryPlugin.defaultPaginationOption = {
    page: 1,
    pageSize: 10
};

/**
 * @param {Schema} schema
 */
module.exports = pageQueryPlugin;